#include "StdAfx.h"
#include "SgMesh.h"


CSgMesh::CSgMesh(void)
{
}

CSgMesh::~CSgMesh(void)
{
}

void CSgMesh::Render(){

	PTex pt = m_tvertices.begin();
	//Norm n = m_normals.begin();
    glBegin(GL_TRIANGLES);
    for(PTV v=m_triangles.begin();  v!=m_triangles.end();  v++)
    {	
	/*		
		if(pt!=m_tvertices.end()){
			glTexCoord2dv(m_tvertices[v->t]);
			pt++;
		}	*/
		glNormal3dv(m_normals[v->n]);
		if(v->t!=-1)
			glTexCoord2dv(m_tvertices[v->v]);
        glVertex3dv(m_vertices[v->v]);
		

		//glTexCoord2dv(m_tvertices[v->t]);
    }
    glEnd();
}

void CSgMesh::AddTriangleVertex(int v, int n, int t)
{
	TV tv;
	tv.v = v;
	tv.n = n;
	tv.t = t;
	m_triangles.push_back(tv);
}

void CSgMesh::AddFlatQuad(int a, int b, int c, int d, int n, int t)
{
	// First triangle
    AddTriangleVertex(a, n, t);
    AddTriangleVertex(b, n, t);
    AddTriangleVertex(c, n, t);

    // Second triangle
    AddTriangleVertex(a, n, t);
    AddTriangleVertex(c, n, t);
    AddTriangleVertex(d, n, t);	
}

void CSgMesh::AddFlatTriangle(int a, int b, int c,  int n, int t)
{
    AddTriangleVertex(a, n, t);
    AddTriangleVertex(b, n, t);
    AddTriangleVertex(c, n, t);
}

//
// Name :         CMesh::ComputeSmoothNormals()
// Description :  Compute a normal for each vertex that is the
//                average of the surface normals incident on the 
//                vertex.
//
void CSgMesh::ComputeSmoothNormals()
{
	m_normals.resize(m_vertices.size());
	for(unsigned int i=0; i<m_vertices.size(); i++)
		m_normals[i] = CGrVector(0, 0, 0, 0);

	for(PTV v=m_triangles.begin(); v!=m_triangles.end(); )
	{
		// Collect up the vertices of a triangle...
		int a = v->v;
		v++;
		int b = v->v;
		v++;
		int c = v->v;
		v++;

		// Surface normal
		CGrVector normal = Cross3(m_vertices[b] - m_vertices[a],
								m_vertices[c] - m_vertices[a]);
		normal.Normalize3();

		// Add to the incident vertices normals
		m_normals[a] += normal;
		m_normals[b] += normal;
		m_normals[c] += normal;
	}

	// Normalize the normals
	for(unsigned int i=0; i<m_vertices.size(); i++)
		m_normals[i].Normalize3();
}

//
// Name :         CMesh::AddQuad()
// Description :  Add a quadrangle to the triangle mesh with no 
//                assumption of flatness.
//
void CSgMesh::AddQuad(int a, int b, int c, int d)
{
    // First triangle
    AddTriangleVertex(a, a, -1);
    AddTriangleVertex(b, b, -1);
    AddTriangleVertex(c, c, -1);

    // Second triangle
    AddTriangleVertex(a, a, -1);
    AddTriangleVertex(c, c, -1);
    AddTriangleVertex(d, d, -1);
}